package gov.nhso.prov.acc.utils;

import gov.nhso.prov.acc.core.ConfigBundle;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.crystaldecisions.sdk.exception.SDKException;
import com.crystaldecisions.sdk.framework.CrystalEnterprise;
import com.crystaldecisions.sdk.framework.IEnterpriseSession;
import com.isud.core.ISUD;
import com.isud.paging.PageBean;
/**
 * 
 * @author Pisanui
 * 
 * Utility RMS System
 * Store session name [userInfo, moduleSys, menuSys, menuAuth, screenCode, msg]
 *
 */
@SuppressWarnings({ "unchecked", "rawtypes"})
public class Utility {
	public String pageRows = ConfigBundle.getValue("PAGEROWS");
	public String schema = ConfigBundle.getValue("SCHEMA");
	public String sysDate = ConfigBundle.getValue("SYSDATE");
	public String ioc = ConfigBundle.getValue("INCOME_OTHER_CODE");
	public String ic = ConfigBundle.getValue("INTEREST_CODE");
	public String rrc = ConfigBundle.getValue("ROLE_REGION_CODE");
	public String dp = ConfigBundle.getValue("DEPLOY_PRODUCTION");
	public String reportHost = ConfigBundle.getValue("REPORT_HOST");
	public String reportUser = ConfigBundle.getValue("REPORT_USER");
	public String reportPassword = ConfigBundle.getValue("REPORT_PASSWORD");
	public String reportType = ConfigBundle.getValue("REPORT_TYPE");
	public String idReport1 = ConfigBundle.getValue("ID_REPORT1");
	public String idReport21 = ConfigBundle.getValue("ID_REPORT21");
	public String idReport22 = ConfigBundle.getValue("ID_REPORT22");
	public String idReport3 = ConfigBundle.getValue("ID_REPORT3");
	public String idReport4 = ConfigBundle.getValue("ID_REPORT4");
	public String idReport5 = ConfigBundle.getValue("ID_REPORT5");
	public String idReport6 = ConfigBundle.getValue("ID_REPORT6");
	public String idReport7 = ConfigBundle.getValue("ID_REPORT7");
	public String idReport81 = ConfigBundle.getValue("ID_REPORT81");
	public String idReport82 = ConfigBundle.getValue("ID_REPORT82");
	public String idReport9 = ConfigBundle.getValue("ID_REPORT9");
	public String idReport10 = ConfigBundle.getValue("ID_REPORT10");
	
	public UserInfo user(HttpServletRequest request) {
		return (UserInfo) request.getSession().getAttribute("userInfo");
	}
	public SysAuth sysAuth(HttpServletRequest request) {
		return new SysAuth(request);
	}
	
	public DataUtil dataUtil(ISUD dao) {
		return new DataUtil(dao);
	}
	
	public GenCode genCode(ISUD dao) {
		return new GenCode(dao);
	}
	
	public BeanUtil beanUtil() {
		return new BeanUtil();
	}

	public Message message(HttpServletRequest request) {
		return new Message(request);
	}
	
	public DateUtil dateUtil() {
		return new DateUtil();
	}
	
	public DigitUtil digitUtil() {
		return new DigitUtil();
	}
	
	public PropUtil properties() {
		return new PropUtil();
	}
	
	public BathText bathText() {
		return new BathText();
	}
	public BathThaiText bathThaiText(){
		return new BathThaiText();
	}
	
	public void initPage(HttpServletRequest request) {
		PageBean pageBean = new PageBean();
		pageBean.setSelectPage("1");
		pageBean.setPageRows(this.pageRows);
		pageBean.setDefaultRows(this.pageRows);
		pageBean.setOrderField("UPDATED_DATE");
		pageBean.setOrderType("DESC");
		request.setAttribute("pageBean", pageBean);
	}
	
	public String quote(String data) {
		if (data != null && !data.equals("")) {
			data = "'" + data + "'";
		} else {
			data = "";
		}
		return data;
	}
	
	public String getAttr(HttpServletRequest request, String name) {
		String data = "" ;
		if (request.getAttribute(name) != null) {
			data = (String) request.getAttribute(name);	
		}
		return data;
	}

	public void clearLastRequest(HttpServletRequest request, String sessionName) {
		HttpSession session = request.getSession();
		session.setAttribute(sessionName, null);
	}
	
	public void setLastRequest(HttpServletRequest request, String sessionName) {
		Map<String, Object> lastRequest = new HashMap<String, Object>();
		HttpSession session = request.getSession();
		Enumeration enumer = request.getAttributeNames();
		while (enumer.hasMoreElements()) {
			String name = (String) enumer.nextElement();
			lastRequest.put(name, request.getAttribute(name));
		}
		enumer = request.getParameterNames();
		while (enumer.hasMoreElements()) {
			String name = (String) enumer.nextElement();
			lastRequest.put(name, this.encodeUTF(request.getParameter(name)));
		}
		session.setAttribute(sessionName, lastRequest);
	}

	public boolean getLastRequest(HttpServletRequest request, String sessionName) {
		boolean haveData = false;
		HttpSession session = request.getSession();
		if (session.getAttribute(sessionName) != null) {
			Enumeration enumer = request.getAttributeNames();
			while (enumer.hasMoreElements()) {
				String name = (String) enumer.nextElement();
				request.setAttribute(name, "");
			}
			enumer = request.getParameterNames();
			while (enumer.hasMoreElements()) {
				String name = (String) enumer.nextElement();
				request.setAttribute(name, "");
			}
			Map<String, Object> map = (Map) session.getAttribute(sessionName);
			int x = 0;
			for (Map.Entry<String, Object> entry : map.entrySet()) {
			    request.setAttribute(entry.getKey(), entry.getValue());
				x++;
			}
			if (x > 0) {
				haveData = true;
			}
		}
		return haveData;
	}

	public String encodeUTF(String str) {
        String output = "";
        try {
	        if (str != null) {
	            try {
	                output = new String(str.getBytes("ISO8859_1"), "UTF-8");
	            } catch (Exception e) {
	            	e.printStackTrace();
	            }
	        }
        } catch (Exception e) {
			e.printStackTrace();
		}
        return output;
    }

	public String fulFill(String str, int maxLength){
		String result = "";
		if (str != null && str.length() <= maxLength) {
			StringBuffer bufferStr = new StringBuffer();
			int i=0;
			bufferStr.append(str);
			if(str.length() < maxLength){
				for(i = str.length();i<maxLength;i++){
					bufferStr.append(" ");
				}
			}
			result = bufferStr.toString();
		} else if (str != null && str.length() > maxLength) {
			result = str.substring(0, maxLength);
		} else {
			StringBuffer bufferStr = new StringBuffer();
			for(int i = 0;i<maxLength;i++){
				bufferStr.append(" ");
			}
			result = bufferStr.toString();
		}
		return result;
	}
	public String thaiNumber(String textNumber){
		String result = "";
		if (textNumber != null && !textNumber.equals("")) {
			result = textNumber;
			result = result.replaceAll("0", "๐");
			result = result.replaceAll("1", "๑");
			result = result.replaceAll("2", "๒");
			result = result.replaceAll("3", "๓");
			result = result.replaceAll("4", "๔");
			result = result.replaceAll("5", "๕");
			result = result.replaceAll("6", "๖");
			result = result.replaceAll("7", "๗");
			result = result.replaceAll("8", "๘");
			result = result.replaceAll("9", "๙");
		}
		return result;
	}
	public String numberFormat(String format, String number) {
		String result = "";
        try {
        	if (number != null && !number.equals("")) {
	        	NumberFormat formatter = new DecimalFormat(format);
	        	result = formatter.format(Double.parseDouble(number.replaceAll("[^.0-9\\.]+", "")));
        	}
        } catch (Exception e) {
        	e.printStackTrace();
		}
        return result;
	}
	public String formatDecimal(double d, int precision){
		String myformat = "###,###,###,###,##0";
		String result = "";
		if (precision == 0){
			DecimalFormat df = new DecimalFormat(myformat);
			return df.format(d).replaceAll("[^.0-9\\.]+", "");
		}
		myformat = "###############.";

		for(int x= 0; x < precision; x++)
		myformat = myformat + "0";

		DecimalFormat df = new DecimalFormat(myformat);
		result = df.format(d);
		result = result.replace(",", "");
		result = result.replace(".", "");
		if (result.length() < 15) {
			int length = 15 - result.length();
			for (int i=0;i<length;i++) {
				result = "0"+result;
			}
		}
		return result;
	}
	public String getToken() {
		String token = "";
		try {
			IEnterpriseSession sess = CrystalEnterprise.getSessionMgr().logon("Administrator", "ProvaccSecure", "PROVACCREPORT:6400", "secEnterprise");
			token = sess.getLogonTokenMgr().createLogonToken("",120,100);
		} catch (SDKException e) {
			e.printStackTrace();
		}
		return token;
	}
}
